﻿using AutoMapper;
using MediatR;
using SmartTracking.API.Read.Application.Commands.EWEQuery;
using SmartTracking.API.Read.EweDTO;
using SmartTracking.ApiRead.Applications.Commands;
using SmartTracking.Domain.EWE;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.ApiRead.Applications.CommandHandlers
{
    public class GetWeaningsCommandHandler : IRequestHandler<GetWeaningsCommand, ApiResult<ApiPaging<MainWeaningDTO>>>
    {
        private readonly IBaseRepository<Weanings> eRep;
        private readonly IMapper mapper;

        public GetWeaningsCommandHandler(
            IBaseRepository<Weanings> eRep,
            IMapper mapper)
        {
            this.eRep = eRep;
            this.mapper = mapper;
        }

        public async Task<ApiResult<ApiPaging<MainWeaningDTO>>> Handle(GetWeaningsCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<MainWeaningDTO>> result = new ApiResult<ApiPaging<MainWeaningDTO>>();
            result.Code = ApiEnum.查询成功;
            result.Message = "查询成功";

            // 获取所有数据
            var list = eRep.GetAll();

            // 时间范围查询：开始时间过滤
            if (request.StartWeaningTime != null)
            {
                list = list.Where(x => x.WeaningTime >= request.StartWeaningTime);
            }

            // 时间范围查询：结束时间过滤
            if (request.EndWeaningTime != null)
            {
                list = list.Where(x => x.WeaningTime <= request.EndWeaningTime);
            }

            // 耳号查询
            if (!string.IsNullOrWhiteSpace(request.WeaningSnowId))
            {
                list = list.Where(x => x.WeaningSnowId == request.WeaningSnowId);
            }

            // 转入栋舍查询
            if (!string.IsNullOrWhiteSpace(request.WeaningTransferhouse))
            {
                list = list.Where(x => x.WeaningTransferhouse == request.WeaningTransferhouse);
            }

            // 负责人查询
            if (!string.IsNullOrWhiteSpace(request.ResponsibleFor))
            {
                list = list.Where(x => x.ResponsibleFor == request.ResponsibleFor);
            }

            // 获取总数
            int totalCount = list.Count();
            int totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);

            // 排序、分页
            list = list.OrderByDescending(x => x.WeaningId)
                       .Skip((request.PageIndex - 1) * request.PageSize)
                       .Take(request.PageSize);

            // 映射到 DTO
            var dataList = mapper.Map<List<MainWeaningDTO>>(list.ToList());

            // 填充分页信息
            ApiPaging<MainWeaningDTO> paging = new ApiPaging<MainWeaningDTO>();
            paging.totalCount = totalCount;
            paging.totalPage = totalPage;
            paging.data = dataList;

            result.data = paging;

            return await Task.FromResult(result);
        }
    }
}
